package org.springframework.security.access.vote;

import org.springframework.security.access.AccessDecisionVoter;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.core.Authentication;

import java.util.Collection;
import java.util.List;

/**
 * @author Dillon
 * @date 2024/7/30
 * @slogan 致敬大师 致敬未来的你
 * @desc 决策管理器实现之一
 */
@Deprecated
public class AffirmativeBased extends AbstractAccessDecisionManager {

	public AffirmativeBased(List<AccessDecisionVoter<?>> decisionVoters) {
		super(decisionVoters);
	}

	/**
	 * 权限决策 只要有一个权限认证成功，则认证成功
	 * 默认一般会使用该认证方式
	 *
	 * @param authentication   认证主体
	 * @param object           请求访问包装
	 * @param configAttributes 当前请求所具有的权限
	 * @throws AccessDeniedException 权限认证异常
	 */
	@Override
	@SuppressWarnings({"rawtypes", "unchecked"})
	public void decide(Authentication authentication, Object object, Collection<ConfigAttribute> configAttributes)
			throws AccessDeniedException {
		int deny = 0;
		for (AccessDecisionVoter voter : getDecisionVoters()) {
			int result = voter.vote(authentication, object, configAttributes);
			switch (result) {
				case AccessDecisionVoter.ACCESS_GRANTED:
					return;
				case AccessDecisionVoter.ACCESS_DENIED:
					deny++;
					break;
				default:
					break;
			}
		}
		if (deny > 0) {
			throw new AccessDeniedException(
					this.messages.getMessage("AbstractAccessDecisionManager.accessDenied", "Access is denied"));
		}
		// 兜底
		checkAllowIfAllAbstainDecisions();
	}

}
